package br.com.unitunes.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.unitunes.model.GenericModel;
import br.com.unitunes.util.HibernateUtil;


public abstract class GenericDAO<T extends GenericModel> {
    
	private final EntityManager entityManager = HibernateUtil.getEntityManagerFactory().createEntityManager();
    
    public abstract Class<T> getModelClass();
    
    public EntityManager getEntityManager() {
        return entityManager;
    }
    
    public void save(T model) {
    	getEntityManager().getTransaction().begin();
    	model = getEntityManager().merge(model);
    	getEntityManager().getTransaction().commit();
    }
    
    public void delete(T model) {
    	getEntityManager().remove(model);
    }
    
	public T get(Long id) {
        return (T) getEntityManager().find(getModelClass(), id);
    }
    
	@SuppressWarnings("unchecked")
	public List<T> list() {
        Query query = getEntityManager().createQuery("SELECT t FROM " + getModelClass().toString() + " t" );
        return query.getResultList();
    }
    
	@SuppressWarnings("unchecked")
	public List<T> executaQuery(Query query, Long maxResults, Long index) {
		if(maxResults != null) {
			query.setMaxResults(maxResults.intValue());
		}		
		if(index != null)
		{
			query.setFirstResult(index.intValue());
		}
		return query.getResultList();
	}
}
